﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.IO;
using System.Web;
using System.Xml;
using Graffiti.Core;
using GraffitiExtras.Utility;

namespace GraffitiExtras.Widgets.PollManager
{
    [WidgetInfo("a7abe913-0de7-45a5-9cc5-6c6c5809f901",
    "Poll Manager",
    "Displays a Poll's voting options or graphs received votes")]
    public class PollManager : Widget
    {
        private const int MAXPOLLITEMS = 10;
        private const string objectManagerName = "GraffitiExtras.Widgets.PollManager::PollObject";
        private Poll currentPoll;

        public PollManager()
        {
            currentPoll = ObjectManager.Get<Poll>(objectManagerName);

            if (currentPoll == null)
                currentPoll = new Poll();

            if(currentPoll.IPAddresses == null)
                currentPoll.IPAddresses = new List<string>();
        }
        public override string Name
        {
            get
            {
                if (string.IsNullOrEmpty(Title))
                    return "Current Poll";
                else
                    return Title + " (Poll Widget)";
            }
        }

        protected override NameValueCollection DataAsNameValueCollection()
        {
            NameValueCollection nvc = base.DataAsNameValueCollection();

            if (currentPoll == null)
            {
                if (nvc != null)
                    foreach (String s in nvc.AllKeys)
                        if (nvc[s].ToString().StartsWith("GPI::"))
                            nvc[s] = "";
            }
            else
            {
                for (int i = 0; i < currentPoll.PollItems.Count; i++)
                    nvc[currentPoll.PollItems[i].PollItemGuid] = currentPoll.PollItems[i].PollItemName;
            }

            return nvc;
        }
        protected override FormElementCollection AddFormElements()
        {
            FormElementCollection fec = new FormElementCollection();
            int i;

            fec.Add(new TextFormElement("Title", "Title", "Enter the title of the Current Poll"));

            if (currentPoll.PollSize < 0)
            {
                for (i = 0; i < MAXPOLLITEMS; i++)
                    fec.Add(new TextFormElement("GPI::" + Guid.NewGuid().ToString(), "Poll Item", "Enter a new Poll Item"));
            }
            else
            {
                for (i = 0; i < currentPoll.PollItems.Count; i++)
                    fec.Add(new TextFormElement(currentPoll.PollItems[i].PollItemGuid, "Poll Item", "Enter a new Poll Item"));
            }

            fec.Add(new CheckFormElement("GPX::DELETE", "Delete Poll", "Check this box if you would like to delete this poll", false));

            return fec;
        }

        public override StatusType SetValues(HttpContext context, NameValueCollection nvc)
        {
            base.SetValues(context, nvc);


            if (currentPoll.PollSize < 0)
            {
                // currentPoll = new GraffitiPoll();

                foreach (String s in nvc.AllKeys)
                    if (nvc[s].ToString() != String.Empty && s.StartsWith("GPI::"))
                        currentPoll.PollItems.Add(new PollItem(s, nvc[s]));
                currentPoll.PollSize = currentPoll.PollItems.Count;
            }
            else
            {
                foreach (String s in nvc.AllKeys)
                    if (s.StartsWith("GPI::"))
                        currentPoll.PollItems.Find(delegate(PollItem gpi) { return gpi.PollItemGuid == s; }).PollItemName = nvc[s];
            }

            if (nvc["GPX::DELETE"] == "on")
            {
                ObjectStore.Destroy(new DataBuddy.Column("Name", System.Data.DbType.String, typeof(string), "Name", false, false), objectManagerName);
                ZCache.RemoveCache("object-" + objectManagerName);
                currentPoll = null;
            }
            else
                ObjectManager.Save(currentPoll, objectManagerName);

            return StatusType.Success;
        }

        public override string RenderData()
        {
            currentPoll = ObjectManager.Get<Poll>(objectManagerName);
            StringWriter data  = new StringWriter();
            XmlTextWriter xml = new XmlTextWriter(data);
            StringBuilder sb = new StringBuilder();
            string reportDirectory = VirtualPathUtility.ToAbsolute("~/graffiti-admin/reporting/");
            string settingsDirectory = VirtualPathUtility.ToAbsolute("~/__utility/reporting/");

            if (currentPoll != null && currentPoll.PollSize > 0)
            {
                if (currentPoll.IPAddresses.Contains(HttpContext.Current.Request.UserHostAddress))
                {
                    xml.WriteStartElement("pie");

                    for (int i = 0; i < currentPoll.PollItems.Count; i++)
                    {
                        xml.WriteStartElement("slice");
                        xml.WriteAttributeString("title", currentPoll.PollItems[i].PollItemName);

                        if (i == 1)
                            xml.WriteAttributeString("pull_out", "true");

                        xml.WriteValue(currentPoll.PollItems[i].PollItemValue);
                        xml.WriteEndElement();
                    }

                    xml.Close();

                    sb.AppendLine("<div id=\"piechart\"><strong>Unable to display the poll results</strong></div>");
                    sb.AppendLine("<script type=\"text/javascript\">");
                    sb.AppendLine("// <![CDATA[");
                    sb.AppendLine("var so = new SWFObject(\"" + reportDirectory + "ampie.swf\", \"ampie\", \"100%\", \"250\", \"4\", \"#ffffff\");");
                    sb.AppendLine("so.addVariable(\"path\", \"" + reportDirectory + "\");");
                    sb.AppendLine("so.addVariable(\"settings_file\", escape(\"" + settingsDirectory + "PollManagerPieGraph.xml\"));");
                    sb.AppendLine("so.addVariable(\"chart_data\",\"" + data.ToString().Replace("\"", "'") + "\");");
                    sb.AppendLine("so.addVariable(\"preloader_color\", \"#999999\");");
                    sb.AppendLine("so.addParam('wmode', 'transparent');");
                    sb.AppendLine("so.write(\"piechart\");");
                    sb.AppendLine(" // ]]>");
                    sb.AppendLine("</script>");
                }
                else
                {
                    sb.AppendLine("<div id=\"error-messages\"></div>");
                    sb.AppendLine("<form action=\"" + HttpContext.Current.Request.Url + "\" method=\"post\" name=\"poll_form\" id=\"poll_form\">");
                    sb.AppendLine("<ul>");

                    for (int i = 0; i < currentPoll.PollItems.Count; i++)
                        sb.Append("<li><input type=\"radio\" name=\"GPI::PollItem\" value=\"" + currentPoll.PollItems[i].PollItemGuid + "\">" + currentPoll.PollItems[i].PollItemName);

                    sb.AppendLine("</ul>");
                    sb.AppendLine("<input type=\"hidden\" name=\"PollSubmitted\" value=\"1\">");
                    sb.AppendLine("<input type=\"button\" value=\" Vote \" onclick=\"Polls.submitPoll('" + VirtualPathUtility.ToAbsolute("~/ajaxExtras.ashx") + "');return false; \" />");
                    sb.AppendLine("</form>");
                }
            }
            return sb.ToString();
        }
    }
}
